"""
通过面向对象的设计方法，使得可以通过调用一个save方法来往MySQL数据库中插数据。

"""
import MySQLdb as db


class Database:

    @classmethod
    def connect(cls):
        if getattr(cls, 'conn', None) is None:
            cls.conn = db.connect(host=host, port=port,
                                  user=user, password=password,
                                  database=database, charset=charset)
            cls.cursor = cls.conn.cursor()

    @classmethod
    def save(cls, sql, args):
        cls.connect()
        cls.cursor.execute(sql, args)
        cls.conn.commit()


class Student:

    tbname = 'student'

    def __init__(self, name, gender, age):
        self.name = name
        self.gender = gender
        self.age = age

    def save(self):
        sql = 'insert into %s' % self.tbname
        sql += ' (name, gender, age) values (%s, %s, %s)'
        args = (self.name, self.gender, self.age)
        Database.save(sql, args)


class Teacher:

    tbname = 'teacher'

    def __init__(self, name, gender, age, subject):
        self.name = name
        self.gender = gender
        self.age = age
        self.subject = subject

    def save(self):
        sql = 'insert into %s' % self.tbname
        sql += ' (name, gender, age, subject) values (%s, %s, %s, %s)'
        args = (self.name, self.gender, self.age, self.subject)
        Database.save(sql, args)


host = 'localhost'
port = 3306
user = 'wsgi'
password = 'abc'
database = 'wsgi'
charset = 'utf8'


if __name__ == '__main__':
    t1 = Teacher('HeyGor', 'Male', 40, 'PYTHON')
    t1.save()
